#include <stdio.h>
#include <math.h>

#include "Plant.h"
#include "include.h"

Plant::Plant( TextureManager * textureManager,
			char * texture,
			Vector2D * textureVertices,
			Vector2D rootPosition, 
			Vector2D growDirection,
			float maxLength,
			float size,
			float mass,
			int numTentacles,
			Tentacle * tentacles)
:Object(textureManager,
		new Material("PlantTexture",0,0,true,0.1,-1),
		0.0,
		rootPosition, 
		Vector2D(0,0),
		Vector2D(0,0),
		NULL,
		0,
		0.0,
		0.0,
		0.0,
		mass,
		false)
{
	this->rootPosition = rootPosition;
	this->growDirection = growDirection;
	this->textureVertices = textureVertices;
	this->numTentacles = numTentacles;
	this->tentacles = tentacles;
	this->maxLength = maxLength;
	decapitated = false;
	time = 0;
	position = rootPosition + !growDirection * maxLength;
	size = size * 0.5;
	vertices = (Vector2D*)malloc(sizeof(Vector2D)*4);
	vertices[0] = Vector2D(-size,size);
	vertices[1] = Vector2D(size,size);
	vertices[2] = Vector2D(size,-size);
	vertices[3] = Vector2D(-size,-size);
	numVertices = 4;
	
	if(textureManager)
	{
		if(!textureManager->LoadTexture(texture))
			printf("Failed to load %s\n", texture);
		material->SetTextureIndex(textureManager->TextureIndex(texture));
	}
	stem = new Beard(&(this->rootPosition), 5, 0.1, maxLength/5, 1000, 0.321,0.569,0.235);
	Vector2D * location = new Vector2D(-size,-size);
	AddKeyPoint(location);
	stem->Grab(this, location);
	CalculateUpVector();
	CalculateMomentOfInertia();
}
Plant::~Plant()
{
	if(tentacles)
	{
		free(tentacles);
		tentacles = NULL;
	}
}
bool Plant::PreThinkEntryPoint(double elapsedTime)
{
	//apply a force to the flower
	time += elapsedTime;
	
	if(!decapitated)
		AddForce(Vector2D(50*cos(2*PI*time), 1500+ 500*sin(2*PI*time)));
	
	for(int i=0; i < numTentacles; i++)
		tentacles[i].Think(elapsedTime);
	if(stem)
		stem->Think(elapsedTime);
		
	if(stem->GetLength() > maxLength * 6)
	{
		stem->Release();
		decapitated = true;
	}
	return false;
}
bool Plant::PreDrawEntryPoint()
{
	if(stem)
		stem->Draw();
	for(int i=0; i < numTentacles; i++)
		tentacles[i].Draw();
	glColor4f(1,1,1,1);
	return false;
}
